package com.javamodeling.android.locationpath;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

public class HttpConnectionUtil {

	public static ResultValue connectWithGet(String uri) {
		
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			
			HttpGet httpGet = new HttpGet(GlobalVariables.SERVER_URL + uri);
			
			HttpResponse response = httpClient.execute(httpGet);
			
			ResultValue resultValue = ResultXmlPullParser.parseResultXml(response.getEntity().getContent());
			
			return resultValue;
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
	
	public static ResultValue connectWithPost(String uri, List<NameValuePair> parameterList) {
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(GlobalVariables.SERVER_URL + uri);
		
		ResultValue resultValue = new ResultValue();
		
		try {
			
			UrlEncodedFormEntity urlEncodedFormEntity = 
				new UrlEncodedFormEntity(parameterList, HTTP.UTF_8);

			httpPost.setEntity(urlEncodedFormEntity);

			HttpResponse response = httpClient.execute(httpPost);
			
			resultValue = ResultXmlPullParser.parseResultXml(response.getEntity().getContent());
			
			return resultValue;
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			resultValue.setResultCodeMinus();
			resultValue.setResultMessage(e.getMessage());
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			resultValue.setResultCodeMinus();
			resultValue.setResultMessage(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			resultValue.setResultCodeMinus();
			resultValue.setResultMessage(e.getMessage());
		}

		return resultValue;
	}
}
